
//get clock time
$.ajax({
   type: 'POST',
   url: root + module + '/getcurrenttime',
   dataType: 'json',
   success: function(data){
		var timestamp = new Date(data.datetime * 1000);
		$("#clock").clock({"timestamp":timestamp});
		initCal(timestamp);
	},
   error: function () { onError(); hideLoader(); }
 });
	 
	 
//load calendar
function initCal(date)
{
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();
	
	$('#calendar').fullCalendar({
		theme: true,
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		selectable: true,
		selectHelper: true,
		disableDragging: true,
		viewDisplay: function(view) { if(view.name!="month") hideBalloon(); },
		select: function(start, end, allDay) {
			// var title = prompt('Event Title:');
			// if (title) {
				// calendar.fullCalendar('renderEvent',
					// {
						// title: title,
						// start: start,
						// end: end,
						// allDay: allDay
					// },
					// true // make the event "stick"
				// );
			// }
			// calendar.fullCalendar('unselect');
		},
		dayClick: function(date, allDay, jsEvent, view) {			
			$('#calendar').fullCalendar('gotoDate', date);
			if(view.name=="month")
				displayBalloon(date);
			else
				hideBalloon();
		},
		eventClick: function(calEvent, jsEvent, view) {

			if(calEvent.type=='punch')
			{
				alert('Punch Alteration coming soon');
			}
			else if(calEvent.type=="punch-alteration")
			{
				
			}

		},
		editable: true,
		eventSources: [

			// your event source
			{
				url: root + module + '/getcalendarevents',
				type: 'POST',				
				cache: true,				
				error: function() {
					alert('there was an error while fetching events!');
				}
			}
			// any other sources...

		],
		loading: function (bool) {
			hideBalloon();		
			if (bool)
			{
				showLoader('.main-calendar');				
			}
			else
			{
				showViewMore();
				hideLoader();
			}
		}
		// eventAfterRender: function( event, element, view ) { 
			// //alert(event.start);
			// var dt = new Date(event.start);
		// }
		
		
	});
}

function showViewMore()
{	
	$('.view-more').remove();
	$('.fc-border-separate td[class*=fc-day]').each(function(){
		if(!$(this).hasClass('fc-other-month'))
		{		
			if($('div[name=groupDay'+$(this).attr('id')+']').length>4)
			{
				$(this).append('<a href="javascript:void(0)" id="'+$(this).attr('id')+'" onclick="viewMoreClick(this)" class="view-more">View More</a>');
			}
		}		
	});
}

function viewMoreClick(element)
{
	var monthday = $(element).attr('id');
	monthday = monthday.split("-");
	var year = $('.fc-header-title h2').html();
	year = year.split(" ");
	var monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	var month=-1
	for (i=0;i<monthNames.length;i++) {
		if(monthNames[i]==monthday[0]) {
			month = i;
			break;
		}
	}
	$('#calendar').fullCalendar('gotoDate', year[1], month, monthday[1]);
	$('.fc-button-agendaDay').trigger('click');
}

function displayBalloon(date)
{
	var d = new Date(date)
	var monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	var month = monthNames[d.getMonth()];
	var date = d.getDate();
	var td = '.fc-content table tbody td#'+month+'-'+date+':not(.fc-other-month)';
	
	var left = $(td).offset().left + 50;
	var top = $(td).offset().top - 105;
	$('.balloon').hide().css('top',top).css('left',left).fadeIn('slow');
	
	$('input[name=selected-date]').val((d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear());
}
function hideBalloon()
{
	$('.balloon').hide();
}

// $(".fc-content tbody tr td").showBalloon({
	// position: "left",
	// offsetX: 50,
	// offsetY: 50,
	// tipSize: 20,
	// css: {
		// maxWidth: "17em",
		// border: "solid 5px #463974",
		// color: "#463974",
		// fontWeight: "bold",
		// fontSize: "130%",
		// backgroundColor: "#efefef",
		// zIndex: "9999999"
	// }
// }).toggle(function() { $(this).hideBalloon(); }, function() { $(this).showBalloon(); });


$('#apply-leave').click(function(){	
	hideBalloon();
	clearDialog();
	
	//display details
	$('#leave-from, #leave-to').val($('input[name=selected-date]').val());
	
	$('.leave-dialog').dialog({
		draggable: false,
		modal: true,
		resizable: false,
		width:455,
		title: 'Apply for Leave'
	});
});

$('#leave-add').click(function(){

	if($('#form-leave').validationEngine('validate'))
	{
		if($('#leave-id').val())
		{
			var leaveFrom = new Date($('#leave-from').val());
			var leaveTo = new Date($('#leave-to').val());
			leaveFrom = leaveFrom.valueOf()/1000;
			leaveTo = leaveTo.valueOf()/1000;
			var dt = {leave_from: leaveFrom, leave_to: leaveTo, leave_id: $('#leave-id').val(), reason: $('#leave-reason').val()};
			$.ajax({
			   type: 'POST',
			   data: dt,
			   url: root + 'leave_applications/additem',
			   dataType: 'json',
			   success: function(data){
					if(data.return=="success")
					{
						alert('Successfully applied leave');
						$('#calendar').fullCalendar( 'refetchEvents' );
						$('.dialog').dialog('close');
					}
					else if(data.return=="error")
						errorFunction();
				},
			   error: function () { onError(); hideLoader(); }
			 });
		}
		else
			alert('Please select a leave type.');
	}    
});

$('#apply-overtime').click(function(){	
	hideBalloon();
	clearDialog();
	//display details
	$('#overtime-date').val($('input[name=selected-date]').val());
	$('.overtime-dialog').dialog({
		draggable: false,
		modal: true,
		resizable: false,
		width:455,
		title: 'Apply for Overtime'
	});	
});

$('#overtime-add').click(function(){

	if($('#form-overtime').validationEngine('validate'))
	{
		alert('apply overtime');
	}    
});

$('#apply-punch').click(function(){	
	hideBalloon();
	clearDialog();
	//display details
	$('#punch-date').val($('input[name=selected-date]').val());
	$('.punch-dialog').dialog({
		draggable: false,
		modal: true,
		resizable: false,
		width:455,
		title: 'Apply for Punch Alteration'
	});	
});

$('#punch-add').click(function(){

	if($('#form-punch').validationEngine('validate'))
	{
		var strDate = $('#punch-date').val() + ' ' + $('#punch-time').val();
		var date = new Date(strDate);
		date = 	date.valueOf()/1000
		var dt = {punchdate: date, is_in_or_out: $('#punch-type').val(), reason: $('#punch-reason').val()};
		$.ajax({
		   type: 'POST',
		   data: dt,
		   url: root + 'punch_alterations/additem',
		   dataType: 'json',
		   success: function(data){
				if(data.return=="success")
				{
					alert('Successfully applied punch alteration');
					$('#calendar').fullCalendar( 'refetchEvents' );
					$('.dialog').dialog('close');
				}
				else if(data.return=="error")
					errorFunction();
			},
		   error: function () { onError(); hideLoader(); }
		 });
	}    
});



function clearDialog()
{
	$('.dialog').validationEngine('hideAll');
	$('.dialog input, .dialog textarea').val('');
	$('.dialog select').val($('.dialog select option:first').val());
}